package com.android.canvasproject.model.listeners;

import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.ClipData;
import android.content.ContentValues;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.android.canvasproject.model.dao.ProviderDaoOpenHelper;
import com.android.canvasproject.model.entity.Postit;
import com.android.canvasproject.view.fragments.PostitDialog;

public class PostitInternal implements OnClickListener, OnTouchListener, View.OnDragListener {

	private Activity activity;

	public PostitInternal(Activity activity) {
		this.activity = activity;
	}

	@Override
	public void onClick(View v) {
		DialogFragment dialogPost = new PostitDialog();
		FragmentManager fragmentManager = activity.getFragmentManager();
		dialogPost.show(fragmentManager, PostitDialog.class.getSimpleName());

	}

	@Override
	public boolean onTouch(View view, MotionEvent motionEvent) {
		if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
			ClipData data = ClipData.newPlainText("", "");
			DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
			view.startDrag(data, shadowBuilder, view, 0);
			view.setVisibility(View.GONE);
			return true;
		}

		return false;
	}

	@Override
	public boolean onDrag(View v, DragEvent event) {
		View view = (View) event.getLocalState();
		
		switch (event.getAction()) {
		case DragEvent.ACTION_DRAG_STARTED:
			break;

		case DragEvent.ACTION_DRAG_ENTERED:
			break;

		case DragEvent.ACTION_DRAG_EXITED:
			break;

		case DragEvent.ACTION_DROP:
			RelativeLayout container = (RelativeLayout) v;
			view.setX(event.getX() - 64f);
			view.setY(event.getY() - 64f);
			ViewGroup owner = (ViewGroup) view.getParent();
			owner.removeView(view);
			container.addView(view);
			view.setVisibility(View.VISIBLE);

			Integer pId = (Integer) (view.getTag() == null ? null : view.getTag());
			ContentValues values = new ContentValues();
			values.put("position_x", view.getX());
			values.put("position_y", view.getY());

			ProviderDaoOpenHelper provider = new ProviderDaoOpenHelper(activity);
			provider.update(Postit.PostitDao.TB_POSTIT, values, "_id = " + pId, null);
			provider.cleanup();

			break;

		case DragEvent.ACTION_DRAG_ENDED:
			if(!event.getResult())
				view.setVisibility(View.VISIBLE);
			break;

		default:
			break;
		}
		
		return true;
	}
}
